#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdbool.h>

#define COMMAND_SIZE 1024

int count_command;
char command[COMMAND_SIZE];

extern char** environ;

#define ENV_SIZE 100

// 进程中的环境变量表。
char* g_env[ENV_SIZE];

int count_env ;

void Get_Env()
{
	for(int i = 0;environ[i];++i)
	{
		g_env[count_env] = (char*)malloc((sizeof(environ[i]) + 1)  * sizeof(char) );
		strcpy(g_env[count_env],environ[i]);
		++count_env;
	}
}



#define ARGC 100

int g_argc;
char* g_argv[ARGC];

const char* GetUSER()
{
	const char* user = getenv("USER");

	return user == nullptr ? "None" : user;
}

const char* GetHOSTNAME()
{
	const char* hostname = getenv("HOSTNAME");

	return hostname == nullptr ? "None" : hostname;
}
 
const char* GetPWD()
{
	const char* pwd = getenv("PWD");

	return pwd == nullptr ? "None" : pwd;
}

void GetCommandId()
{
	#define REMIND "$"
	snprintf(command,sizeof(command) - 1,"%s@%s%s %s ",GetUSER(),GetHOSTNAME(),GetPWD(),REMIND);

	printf("%s",command);
	count_command = strlen(command);
	memset(command,0,count_command * sizeof(char));
	
}

void Separa_Line(char* str,int size)
{
	#define SEP " "
	g_argv[g_argc++] = strtok(str,SEP);

	while(g_argv[g_argc++] = strtok(NULL,SEP))
	{
		;
	}

	g_argv[g_argc] = nullptr;
}

void GetCommand()
{
	#define STR_SIZE 100
	char str[STR_SIZE];
	int size = 0;

	char* c = fgets(str,(sizeof(str) - 1) * sizeof(char),stdin);
	if(c == nullptr)
	{
		exit(1);
	}

	size = strlen(str) - 1;
	str[size] = 0;

	Separa_Line(str,size);
}

//#define IN_SIZE 100

//char* InCommand[IN_SIZE];

#define CWD_SIZE 1024

int count_cwd;
char g_cwd[CWD_SIZE];

bool Cd()
{
	int ret = 0;

	if(g_argv[1] == nullptr)
	{
		;
	}
	else if(g_argv[1] == "-")
	{
		;
	}
	else if(g_argv[1] == "~")
	{
		;
	}
	else
	{
		ret = chdir(g_argv[1]);
	}

	if(ret == -1)
	{
		exit(1);
	}

	return ret == 0 ? true : false;
}

//bool Echo()
//{
//	if()
//	{
//		;
//	}
//
//
//}
//
bool InRun()
{
	if(g_argv[0] == "cd")
	{	
		return Cd();
	}
//	else if(g_argv[0] == "echo")
//	{
//		return Echo();
//	}

	g_argc = 0;

	return false;
}

void Exce()
{
	int rid = fork();

	if(rid == 0)
	{
		execvp(g_argv[0],g_argv);
		if(rid == -1)
		{
			exit(1);
		}

		exit(0);
	}

	g_argc = 0;

	waitpid(rid,nullptr,0);
}

int main()
{
	while(1)
	{
		// 1. 打印命令行前的信息。
		GetCommandId();
		
		// 2.输入命令和处理命令行
		GetCommand();
		
		// 3.判断是否有输入，无输入就重新读取。
		if(g_argv[0] == nullptr)
		{
			continue;
		}

		// 4.执行内建命令。同时查看是否是内建命令，不是则不执行。
		if(InRun())
		{
			continue;
		}
		
		// 5.执行外部命令。
		Exce();
	}

	return 0;
}
